package com.bawei.monthdemo2207a.month01.mine

import android.content.Context
import android.util.Log
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.LocationOn
import androidx.compose.material3.Button
import androidx.compose.material3.Divider
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import com.baidu.geofence.GeoFence
import com.baidu.geofence.GeoFenceClient
import com.baidu.geofence.GeoFenceClient.GEOFENCE_IN_OUT_STAYED
import com.baidu.geofence.GeoFenceListener
import com.baidu.geofence.model.DPoint
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.baidu.mapapi.SDKInitializer
import com.baidu.mapapi.map.BaiduMap
import com.baidu.mapapi.map.BitmapDescriptorFactory
import com.baidu.mapapi.map.CircleOptions
import com.baidu.mapapi.map.MapView
import com.baidu.mapapi.map.MarkerOptions
import com.baidu.mapapi.map.MyLocationData
import com.baidu.mapapi.model.LatLng
import com.bawei.monthdemo2207a.App
import com.bawei.monthdemo2207a.R
import com.bawei.monthdemo2207a.uitls.DateFormatUtil
import com.blankj.utilcode.util.ToastUtils
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.Date


/**
 * 作者：赵亮
 * 时间：2024/12/26 16:05
 * 功能：我的页面
 */

lateinit var mMapView: MapView
lateinit var mBaiduMap: BaiduMap
lateinit var mLocationClient: LocationClient
var latitude = 39.90923
var longitude = 116.447428

@Composable
fun MinePage() {

    var lat by remember {
        mutableStateOf(latitude)
    }

    var long by remember {
        mutableStateOf(longitude)
    }

    /**
     * 签到按钮是否可用
     */
    var isEnable by remember {
        mutableStateOf(true)
    }

    var time by remember {
        mutableStateOf(Date())
    }

    LaunchedEffect(key1 = "") {
        launch {
            while (true) {
                delay(1000)
                time = Date()
            }
        }
    }

    Column {


        initBaiDuMap()
        AndroidView(modifier = Modifier.weight(1f), factory = {
            mMapView = MapView(it)
            mBaiduMap = mMapView.map
            mBaiduMap.isMyLocationEnabled = true
            // 添加电子围栏
            val latLng = LatLng(39.90923, 116.447428)
            mBaiduMap.addOverlay(
                CircleOptions().center(latLng).radius(1500).fillColor(R.color.purple_200)
            )
            mBaiduMap.addOverlay(
                MarkerOptions().position(latLng)
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.car))
            )
            mMapView
        })
        Column(
            modifier = Modifier
                .weight(1f)
                .fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally
        ) {
            OutlinedTextField(value = "$lat", onValueChange = {
                lat = it.toDouble()
                latitude = lat
                if (latitude < 39.90923) {
                    isEnable = false
                    ToastUtils.showShort("不在打卡范围内")
                } else {
                    isEnable = true
                }
            })
            OutlinedTextField(value = "$long", onValueChange = {
                long = it.toDouble()
                longitude = long
                if (longitude > 116.447428) {
                    isEnable = false
                    ToastUtils.showShort("不在打卡范围内")
                } else {
                    isEnable = true
                }
            })
            Button(onClick = { /*TODO*/ }, enabled = isEnable) {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Icon(imageVector = Icons.Default.LocationOn, contentDescription = null)
                    Divider(
                        modifier = Modifier
                            .width(1.dp)
                            .height(20.dp)
                    )
                    Text(text = "内勤签到\n${DateFormatUtil.formatTimeSecond.format(time)}")
                }
            }
        }

    }
}

// 初始化百度地图
fun initBaiDuMap() {
    SDKInitializer.setAgreePrivacy(App.context, true)
    SDKInitializer.initialize(App.context)


    LocationClient.setAgreePrivacy(true)
    //定位初始化
    mLocationClient = LocationClient(App.context)


    //通过LocationClientOption设置LocationClient相关参数
    val option = LocationClientOption()
    option.isOpenGps = true // 打开gps
    option.setCoorType("bd09ll") // 设置坐标类型
    option.setScanSpan(1000)


    //设置locationClientOption
    mLocationClient.setLocOption(option)


    //注册LocationListener监听器
    val myLocationListener = MyLocationListener()
    mLocationClient.registerLocationListener(myLocationListener)

    //开启地图定位图层
    mLocationClient.start()

}

class MyLocationListener : BDAbstractLocationListener() {
    override fun onReceiveLocation(location: BDLocation) {
        //mapView 销毁后不在处理新接收的位置
        if (location == null || mMapView == null) {
            return
        }
        val locData = MyLocationData.Builder()
            .accuracy(location.radius) // 此处设置开发者获取到的方向信息，顺时针0-360
            .direction(location.direction).latitude(latitude)
            .longitude(longitude).build()
        mBaiduMap.setMyLocationData(locData)
    }
}

@Preview
@Composable
fun MinePagePreview() {
    MinePage()
}

